package com.luojing.springcloud.config.alimq;


import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.clients.producer.RecordMetadata;

import java.util.Properties;
import java.util.concurrent.Future;

/**
 * Created by luojing on 2017/7/4.
 */
public class Producer1 {

    private KafkaProducer<String, String> producer;

    public KafkaProducer<String, String> getProducer() {
        return producer;
    }

    public void setProducer(KafkaProducer<String, String> producer) {
        this.producer = producer;
    }

    public boolean send(String message,String topicStr){
        String topic = System.getProperty("kafka.ons.TOPIC", topicStr);
        Future<RecordMetadata> metadataFuture = producer.send(new ProducerRecord<String, String>(
                topic,
                null,
                System.currentTimeMillis(),
                String.valueOf(message.hashCode()),
                message));
        try {
            RecordMetadata recordMetadata = metadataFuture.get();
            System.out.println("produce ok:" + recordMetadata.toString());
        } catch (Exception e) {
            System.out.println("error occurred");
            e.printStackTrace();
            return false;
        }
        producer.flush();
        return true;
    }
}
